package io.github.talelin.latticy.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.benmanes.caffeine.cache.Cache;
import io.github.talelin.autoconfigure.exception.NotFoundException;
import io.github.talelin.autoconfigure.exception.ParameterException;
import io.github.talelin.core.token.DoubleJWT;
import io.github.talelin.core.token.Tokens;
import io.github.talelin.latticy.dto.MobileLoginDTO;
import io.github.talelin.latticy.entity.User;
import io.github.talelin.latticy.mapper.NewUserMapper;
import io.github.talelin.latticy.model.NewUserDO;
import io.github.talelin.latticy.repository.UserRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Service
public class NewUserService extends ServiceImpl<NewUserMapper, NewUserDO>
{
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private Cache<String, Object> cache;

    @Autowired
    private CollectFlowerService collectFlowerService;

    @Autowired
    private DoubleJWT jwt;

    @Transactional
    public Tokens createToken(MobileLoginDTO dto)
    {
        Map<String, Object> map = (HashMap)cache.asMap().get(dto.getMobile()+"_"+dto.getCode());
        if (map == null) {
            throw new ParameterException(20001);
        }
        String code = map.get("code").toString();
        if (!code.equals(dto.getCode())) {
            throw new ParameterException(20001);
        }
        User user = this.getUserByMobile(dto.getMobile());
        //收花
        collectFlowerService.create(dto.getMobile(), user.getId());
        return jwt.generateTokens(user.getId());
    }

    public User getUserByMobile(String mobile)
    {
        User user = userRepository.findByMobile(mobile);
        if (user == null) {
            user = new User();
            user.setMobile(mobile);
            userRepository.save(user);
        }
        return user;
    }

    public User getCurrentUser(Long id)
    {
        Optional<User> user = userRepository.findById(id);
        return user.orElseThrow(() -> new NotFoundException(10021));
    }


    /**************************** 后台 *******************************/
    public NewUserDO getUser(Long id)
    {
        NewUserDO user = this.getById(id);
        if (user == null) {
            throw new NotFoundException(10021);
        }
        return user;
    }

    public void delete(Long id)
    {
        this.getUser(id);
        this.baseMapper.deleteById(id);
    }


}
